using CodePen.Server.Language;
using Microsoft.AspNetCore.Mvc;

namespace CodePen.Server.Service;

/// <summary>
/// 
/// </summary>
[ApiExplorerSettings(GroupName = "CodePen")]
public partial class CategoryService : IApplicationService
{
    /// <summary>
    /// 
    /// </summary>
    private readonly SugarRepository<PickCategory> _thisRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="currentUser"></param>
    public CategoryService(SugarRepository<PickCategory> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }    

    /// <summary>
    /// 获取Dashboard分类统计数据
    /// </summary>
    /// <returns>返回分类统计数据</returns>
    public async Task<RestfulResult<object>> GetDashboardStatsAsync()
    {
        var restful = new RestfulResult<object>() { Code = CodeStatus.OK };
        
        // 根据用户权限过滤数据，并添加IsDelete条件
        var query = _thisRepository.AsQueryable();;

        // 获取所有分类数据
        var allCategories = await query.ToListAsync();
        
        // 计算统计数据
        var totalCategories = allCategories.Count;
        var activeCategories = allCategories.Count(c => c.IsDisable == YesOrNot.N);
        var disabledCategories = totalCategories - activeCategories;
        
        // 构建返回数据
        restful.Data = new
        {
            totalCategories,
            activeCategories,
            disabledCategories
        };
        
        return restful;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult<PageResult<PickCategory>>> GetPagesAsync(CategoryPageParam? data)
    {
        var restful = new RestfulResult<PageResult<PickCategory>>() { Code = CodeStatus.OK };
        data ??= new CategoryPageParam { PageNo = 1, PageSize = 10 };
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!_currentUser.IsTenantAdmin&&!_currentUser.IsSuperAdmin, u => u.Creator == _currentUser.UserId)
            .WhereIF(data.Code.NotNullOrWhiteSpace(),u=>u.Code==data.Code)
            .WhereIF(data.Name.NotNullOrWhiteSpace(),u=>u.Name.Contains(data.Name))
            .WhereIF(data.IsDisable.HasValue,u=>u.IsDisable==data.IsDisable)
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 所有
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<PickCategory>>> GetlistAsync()
    {
        var restful = new RestfulResult<PageResult<PickCategory>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 100 };
        var query = await _thisRepository.AsQueryable()
             .Where(u => u.IsDisable == YesOrNot.N)
             .OrderByDescending(u => u.CreateTime)
             .ToPageAsync(data.PageNo, data.PageSize);
        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork] 
    public async Task<RestfulResult> AddAsync(PickCategory data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        var isExist = await _thisRepository.IsAnyAsync(u => u.Name == data.Name || u.Code == data.Code  );
        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }
        data.Creator = _currentUser.UserId;
        bool result = await _thisRepository.InsertAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.add}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync(PickCategory data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        var isExist = await _thisRepository.IsAnyAsync(u => (u.Name == data.Name || u.Code == data.Code) &&u.Id == data.Id  );
        if (!isExist)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }
        bool result = await _thisRepository.UpdateAsync(data, true, true, $"{i18n.modify}");
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.modify}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (data.Id == 0)
        {
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
        bool isDelete = await _thisRepository.DeleteByIdAsync(data.Id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.success}";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
    }
}

